package com.pinyougou.show.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import util.FastDFSClient;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@RestController
@RequestMapping("upload")
public class UploadFileController {

    /*读取配置文件中的服务路径名*/
    @Value("${FILE_SERVER_PATH}")
    private String fileServerPath;

    /*注入响应对象*/
    @Autowired
    private HttpServletResponse response;

    /**
     * 图片上传
     * @param imgFile
     * @return
     */
    @RequestMapping
    public void imgUpload(@RequestParam("imgFile") MultipartFile[] imgFile) {

        try {
            //获取输出对象
            PrintWriter out = response.getWriter();

            /*文件上传工具类*/
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
            
            /*循环遍历数组，获取每一个文件*/
            for (MultipartFile file : imgFile) {

                /*获取文件字节数组*/
                byte[] bytes = file.getBytes();
                
                /*获取文件后缀名*/
                String filename = file.getOriginalFilename();
                String ext = filename.substring(filename.lastIndexOf('.')+1);

                //上传,获取文件存储路径
                String path = fastDFSClient.uploadFile(bytes, ext);


                /*print()打印需要json格式，针对于kindEditer富文本编辑器*/
                HashMap map = new HashMap<>();

                /*error=0表示成功*/
                map.put("error",0);
                /*url表示文件完整路径*/
                map.put("url",fileServerPath+path);


                /*将集合转为json格式*/
                String json = JSON.toJSONString(map);

                /*打印一下信息*/
                System.out.println("文件上传over："+json);

                out.print(json);

            }

            /*关闭输出对象*/
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
